// pages/saleCollect/saleCollect.ts
import Dialog from '@vant/weapp/dialog/dialog';
import api from '../../api/index';
import { formatDate } from '../../utils/util';
const app = getApp();
const { manageSites } = app.globalData.userInfo;
const sitePoolObj: any = {};
manageSites.forEach((site: SiteItem) => {
  sitePoolObj[site.siteName] = site.pools.map((pool) => {
    return pool.poolNo;
  });
});
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userName: app.globalData.userInfo.userName,
    defaultDate: Date.now(),
    date: new Date().getTime(),
    formatDate: formatDate(new Date()),
    poolNo: '',
    show: false,
    saleNum: 0,
    weight: 0,
    loading: false,
    isAEel: false,
    minDate: new Date().getTime() - 30 * 86400000,
    maxDate: new Date().getTime(),
    pickerShow: false,
    columns: [] as any[],
    dialogShow: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    const app = getApp();
    if (!app.globalData.isLogin) {
      wx.redirectTo({
        url: '/pages/login/login',
        success: () => {
          console.log('重定向到登录页成功');
        },
        fail: (err) => {
          console.log('重定向到登录页失败', err);
        }
      });
    }
    if (Object.keys(sitePoolObj).length > 0) {
      this.setData({
        columns: [
          {
            values: Object.keys(sitePoolObj),
          },
          {
            values: sitePoolObj[Object.keys(sitePoolObj)[0]],
          },
        ],
      })
    };
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() { },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() { },
  /**
   * 日期选择弹窗显示/关闭/确认
   */
  onCalendarDisplay() {
    this.setData({
      show: true,
    });
  },
  onCalendarClose() {
    this.setData({
      show: false,
    });
  },
  onCalendarConfirm(event: any) {
    this.setData({
      show: false,
      date: event.detail.getTime(),
      formatDate: formatDate(event.detail),
    });
  },
  /**
    * 塘号选择弹窗显示/关闭/确认
    */
  /**
   * 塘号选择弹窗显示/关闭/确认
   */
  onPoolPickerDisplay() {
    if (this.data.columns.length > 0) {
      this.setData({
        pickerShow: true,
      });
    } else {
      return Dialog.alert({
        message: '获取不到您所管理的场塘信息！',
      }).then(() => {
        // on close
      });
    }
  },
  onPoolPickerClose() {
    this.setData({
      pickerShow: false,
    });
  },
  onPoolPickerConfirm(event: any) {
    this.setData({
      pickerShow: false,
      poolNo: event.detail.value[1]
    });
  },
  onPickerChange(event: any) {
    const { picker, value, index } = event.detail;
    picker.setColumnValues(1, sitePoolObj[value[0]]);
  },
  /**
 * 对话框确认按钮异步方法
 * */
  beforeClose(action: string) {
    return new Promise((resolve) => {
      if (action === 'confirm') {
        api.reportSale({
          poolNo: this.data.poolNo,
          saleType: this.data.isAEel ? 1 : 0,
          date: this.data.date,
          quantity: this.data.saleNum,
          weight: this.data.weight,
          reporter: this.data.userName
        }).then(res => {
          resolve(res);
          if (res.status === 200) {
            this.setData({
              dialogShow: true
            })
          }
        }).catch(err => {
          console.log(err);
        })
      } else {
        // 拦截取消操作
        resolve(true);
      }
    });
  },
  onBtnClick() {
    if (this.data.saleNum === null || this.data.weight === null || this.data.saleNum === undefined || this.data.weight === undefined || !this.data.poolNo) {
      return Dialog.alert({
        title: '上报失败',
        message: '有数据内容为空，请检查后再重新上报！',
      }).then(() => {
        // on close
      });
    }
    return Dialog.confirm({
      title: '请再次确认上报信息',
      message: `上报人：${this.data.userName}\n发生日期：${this.data.formatDate}\n塘号：${this.data.poolNo}\n是否A鳗：${this.data.isAEel ? '是' : '否'}\n销售量：${this.data.saleNum} 尾\n销售重量：${this.data.weight} kg`,
      beforeClose: this.beforeClose,
    });
  },
  onSaleNumChange(e: any) {
    this.setData({
      saleNum: Number(e.detail)
    })
  },
  onWeightChange(e: any) {
    this.setData({
      weight: Number(e.detail)
    })
  },
  /**
   * 开关点击
   */
  onSwitch() {
    const flag = this.data.isAEel;
    this.setData({
      isAEel: !flag,
    });
  },
  onDialogClose() {
    this.setData({ dialogShow: false });
  },
});
